package com.excellence.controller;

import com.excellence.datamodel.Result;
import com.excellence.pojo.Manager;
import com.excellence.pojo.User;
import com.excellence.service.impl.ManagerServiceImpl;
import com.excellence.service.impl.UserServiceImpl;
import com.excellence.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @author 徐瑞琪
 */

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    ManagerServiceImpl managerService;

    //用户登录
    @PostMapping("/login/user")
    public Result userLogin(@RequestBody User user) {
        log.info("登录操作，实体为{}", user);
        User res = userService.userLogin(user);
        if (res == null) {
            return Result.success(401, "账号或密码错误！");
        }
        HashMap<String, Object> userDate = new HashMap<>();
        userDate.put("id", String.valueOf(res.getUserId()));
        userDate.put("username", user.getUserUsername());
        res.setToken(JwtUtil.genToken(userDate));
        return Result.success(200, "登录成功", res);
    }

    //管理员登录
    @PostMapping("/login/manager")
    public Result managerLogin(@RequestBody Manager manager) {
        log.info("登录操作，实体为{}", manager);
        Manager res = managerService.selectById(manager);
        if (res == null) {
            return Result.success(200, "登录失败");
        }
        HashMap<String, Object> userDate = new HashMap<>();
        userDate.put("id", String.valueOf(res.getManagerId()));
        userDate.put("username", res.getManagerUsername());
        return Result.success(200, "登录成功", JwtUtil.genToken(userDate));
    }
}
